package com.qtu.product_service.controller;

import com.qtu.entity.BmMember;
import com.qtu.product_service.entity.ProductMapper;
import com.qtu.product_service.feign.HomeFeign;
import com.qtu.product_service.service.HomeService;
import com.qtu.util.CacheUtil;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
@Controller
@RequestMapping("api/product")
public class HomeController {

    @Autowired
    private HomeService homeService;

    @Autowired
    private HomeFeign homeFeign;

    @ApiOperation("秒杀商品查询")
    @ResponseBody
    @RequestMapping("getHotGoods")
    public ConcurrentHashMap<Object, Object> getHotGoods(String token, String killIds){
        int count = 3;//获取3条
        try {
            Object obj = homeFeign.get(token);//从Redis获取店铺数据
            BmMember member = (BmMember) CacheUtil.linkedHashMapToObject(obj, BmMember.class);
            ConcurrentHashMap<Object, Object> map = homeService.getHotGoods(member.getId(), count, killIds);//参数：店铺ID
            return map;
        } catch (Exception e) {
            log.error("秒杀商品查询异常："+e);
        }
        return null;
    }

    @ApiOperation("新品推荐查询")
    @ResponseBody
    @RequestMapping("getNewGoods")
    public List<ProductMapper> getNewGoods(String token,String newIds){
        int time = 7;//最近7天新增商品
        int count = 3;//获取3条
        return getNewGoodsMappers(token,time,count,newIds);
    }

    @ApiOperation("新品推荐查询：更多")
    @ResponseBody
    @RequestMapping("getNewGoodsMore")
    public List<ProductMapper> getNewGoodsMore(String token,String newIds){
        int time = 7;//最近7天新增商品
        int count = 100;//获取100条
        return getNewGoodsMappers(token,time,count,newIds);
    }

    private List<ProductMapper> getNewGoodsMappers(String token,int time,int count,String newIds) {
        try {
            Object obj = homeFeign.get(token);//从Redis获取店铺数据
            BmMember member = (BmMember) CacheUtil.linkedHashMapToObject(obj, BmMember.class);
            List<ProductMapper> newGoods = homeService.getNewGoods(member.getId(),time,count,newIds);//参数：店铺ID
            return newGoods;
        } catch (Exception e) {
            log.error("新品推荐查询异常："+e);
        }
        return null;
    }


    @ApiOperation("商品详情查询")
    @ResponseBody
    @RequestMapping("getGoodsOne")
    public List<ProductMapper> getGoodsOne(String token,int goodsId){
        try {
            List<ProductMapper> goodsOne = homeService.getGoodsOne(goodsId);
            return goodsOne;
        } catch (Exception e) {
            log.error("商品详情查询异常："+e);
        }
        return null;
    }
}
